/*	ResearchUpgrade class definition.
 *
*/

#include "ResearchUpgrade.h"

void ResearchUpgrade::Enter()
{
	DEBUG_PRINT("ResearchUpgrade(%p) %s entering\n", this, type.getName().c_str());

}

void ResearchUpgrade::Execute()
{
	DEBUG_PRINT("ResearchUpgrade(%p) %s executing\n", this, type.getName().c_str());
	
	if(upgrader)
	{
		BB->SpendGas(type.gasPrice(upgradeLevel));
		BB->SpendMinerals(type.mineralPrice(upgradeLevel));
		upgrader->upgrade(type);
		++upgradeLevel;
	}
	control->FinishWithSuccess();
}

void ResearchUpgrade::Exit()
{
	DEBUG_PRINT("ResearchUpgrade(%p) %s exiting\n", this, type.getName().c_str());
	upgrader = NULL;
}

bool ResearchUpgrade::CheckConditions()
{
	DEBUG_PRINT("ResearchUpgrade(%p) %s checking conditions\n", this, type.getName().c_str());
	std::list<BWAPI::Unit*>* upgraders = BB->GetBuildingsByTypeGeneral(type.whatUpgrades());
	if(upgraders)
	{
		for(std::list<BWAPI::Unit*>::iterator it = upgraders->begin(); it != upgraders->end(); it++)
		{
			if(!(*it)->isUpgrading() && BWAPI::Broodwar->canUpgrade(*it,type))
			{
				upgrader = *it;
				break;
			}	
		}
		if(upgrader)
		{
			DEBUG_PRINT("ResearchUpgrade(%p) %s checked conditions and has %d minerals to spend\n", this, type.getName().c_str(), BB->GetMineralsToSpend());
			return true;
		}
		/*if(BB->isResearch(type,upgradeLevel))
		{
			
		}*/
	}
	return false;
}